package com.caineng.zhaobiao.zbapi.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.caineng.zhaobiao.zbapi.dao.CaiSystemLogsDao;
import com.caineng.zhaobiao.zbapi.service.UserService;
import com.caineng.zhaobiao.zbapi.utils.AjaxResult;
import com.caineng.zhaobiao.zbapi.utils.cache.CacheUtils;
import com.caineng.zhaobiao.zbapi.utils.email.MyEmailUtil;
import com.caineng.zhaobiao.zbapi.utils.ip.AddressUtils;
import com.caineng.zhaobiao.zbapi.utils.ip.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class CainengPreLoginInterceptor extends HandlerInterceptorAdapter {

    /**
     * 配置含义
     * 1分钟每个url的访问次数不超过10次
     */
    private static final long TIME_OUT = 1000*60 ; //一分钟
    private static final int MAX_SIZE = 60 ; //最大访问10次

    private CaiSystemLogsDao logsDao = SpringUtil.getBean(CaiSystemLogsDao.class);
    private UserService userService = SpringUtil.getBean(UserService.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String curDevice = request.getHeader("platform");
        /*//客户端信息

        String userAgent = request.getHeader("user-agent") ;
        String token = request.getHeader("cainengtoken") ;
        String location = request.getParameter("location") ;

        String ip = IpUtils.getIpAddress(request);
        log.info(" curDevice "+curDevice+ip+"  location:"+ location+" url== "+request.getRequestURI()+"  cainengtoken: "+token);
        String path = request.getRequestURI();
        CaiSystemLogs systemLogs = new CaiSystemLogs() ;

        systemLogs.setIp(ip);
        systemLogs.setAreaName(path+" IP:"+ip+":"+AddressUtils.getRealAddressByIP(ip)+" LBS: "+location);
        systemLogs.setCurDevice(curDevice);
        systemLogs.setUserAgent(userAgent);
        systemLogs.setDate(DateUtil.now());



        if (StpUtil.isLogin()) {
            // 获取当前会话账号id, 如果未登录，则抛出异常：`NotLoginException`
            String userId = StpUtil.getLoginIdAsString();
            //log.info("进来缓存.....");
            CaiBaseUser loginUser = userService.findUserByIdCache(userId);
            if (loginUser != null) {
                systemLogs.setUserPhone(loginUser.getPhone());
                systemLogs.setUsername(loginUser.getShowName());
            }
        }
        log.info(JSONUtil.toJsonStr(systemLogs));
        logsDao.insert(systemLogs);*/
        //IP限制
        if(!validateCode(request)){
            MyEmailUtil myEmailUtil = SpringUtil.getBean(MyEmailUtil.class) ;
            myEmailUtil.sendSimpleMail("访问次数超限",curDevice+"     "+request.getRequestURI()+"     "+ IpUtils.getIpAddress(request));
            AjaxResult res = AjaxResult.maxByDay("客官，稍微慢点儿，休息一下再试！");
            String jsonStr = JSONUtil.toJsonStr(res);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().println(jsonStr);
            response.getWriter().close();
            return false ;
        }

        /*if(StringUtils.isBlank(curDevice)){
            logService.addAbnormal("非正常途径进入");
            return false;
        }*/
        return true;
    }

    /**
     * 接口的访问频次限制
     *
     * @param request
     * @return
     */
    private boolean validateCode(HttpServletRequest request) {

        boolean resultCode = true;
        try {
            String ip = request.getParameter("ip");
            if(StrUtil.isBlank(ip)) {
                ip = AddressUtils.getRealIpAddr(request);
            }
            String url = request.getRequestURL().toString();
            log.info("用户IP[" + ip + "]"+url);
            String key = "req_limit:".concat(url).concat(ip);
            Long count = (Long) CacheUtils.get(key);
            if(count==null){
                count=1L;
                CacheUtils.put(key,count,TIME_OUT);

            }else{
                count++;
                CacheUtils.put(key,count,TIME_OUT);
            }
            if (count > MAX_SIZE) {
                log.error("用户IP[" + ip + "]访问地址[" + url + "]超过了限定的次数[" + MAX_SIZE + "]");
                resultCode = false;
            }
        } catch (Exception e) {
            log.error("发生异常: ", e);
        }
        return resultCode;
    }

    public static void main(String[] args) {
        String url = "http://127.0.0.1:8200/zbapi/zbapi/index/bigEventGray";
        for (int i = 0; i < 12; i++) {
            String logsStr = HttpUtil.post(url,"",6000);
            System.out.println(logsStr+"=======");
        }

    }

}
